<?php 
/**
 * 闪购商品处理
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: bonus.php 17217 2011-01-19 06:29:08Z liubo $
*/


// exit();
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
// /* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

// ）

// //闪购商品列表

if( $_REQUEST['act'] == "list"){



    $smarty->assign('ur_here', "闪购列表");
    $smarty->assign('action_link', array('href' => 'limit.php?act=add', 'text' => "添加闪购商品"));
    $smarty->assign('full_page',    1);
    //获取闪购列表
    $limit_list=limit_list();
    $smarty->assign('agency_list',  agency_list());//办事处列表
    $smarty->assign('limit_list',   $limit_list['goods']);
    $smarty->assign('filter',       $limit_list['filter']);
    $smarty->assign('record_count', $limit_list['record_count']);
    $smarty->assign('page_count',   $limit_list['page_count']);
	$smarty->display('limit_list.htm');
}
//订单列表分页
elseif ($_REQUEST['act'] == 'query')
{
    /* 检查权限 */
    admin_priv('snatch_manage');
    $limit_list = limit_list();//订单列表
    $smarty->assign('limit_list',   $limit_list['goods']);
    $smarty->assign('filter',       $limit_list['filter']);
    $smarty->assign('record_count', $limit_list['record_count']);
    $smarty->assign('page_count',   $limit_list['page_count']);

    make_json_result($smarty->fetch('limit_list.htm'), '', array('filter' => $limit_list['filter'], 'page_count' => $limit_list['page_count']));
}





//添加闪购商品
if( $_REQUEST['act'] == "add"){
	$smarty->assign('agency_list',  agency_list());//办事处列表
	//处理商品提交数据
	// 	$keyword='3794';

	// $where .= " AND (g.goods_id LIKE '%" . mysql_like_quote($keyword) . "%' OR gs.goods_sku LIKE '%" . mysql_like_quote($keyword) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($keyword) . "%')";
	// $sql=" SELECT g.goods_id,g.goods_name,gs.area_id, ga.agency_name,gs.goods_number,g.shop_price,g.promote_start_date,g.promote_end_date,g.goods_sku ".
	// 	 " FROM ".$GLOBALS['ecs']->table('goods') ." AS g ".
	// 	 " LEFT JOIN ". $GLOBALS['ecs']->table('goods_stock') ." AS gs ON g.goods_sku = gs.goods_sku ".
	// 	 " LEFT JOIN ". $GLOBALS['ecs']->table('agency') ." AS ga ON agency_id = gs.area_id ".
	// 	 " WHERE  g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".$where;

	// $goods_list=$db->getAll($sql);
	// $smarty->assign('goods_list',   $goods_list);
	if($_REQUEST['step'] == "complete"){
		// $area_id            = $_REQUEST['area_id'];
		$goods_id			= $_REQUEST['goods_id'];
		$goods_sku          = $_REQUEST['goods_sku'];
		$limit_num			= $_REQUEST['limit_num'];
		$goods_num          = $_REQUEST['goods_num'];
		$promote_price      = $_REQUEST['promote_price'];
		$promote_start_date = strtotime($_REQUEST['promote_start_date']);
		$promote_end_date   = strtotime($_REQUEST['promote_end_date']);
		//重组数据
		foreach ($goods_sku as $key => $value) {
            $limit_goods[$key]['goods_sku']     = $value;
            $limit_goods[$key]['area_id']       = 3;
            $limit_goods[$key]['goods_id']      = $goods_id[$key];
            $limit_goods[$key]['goods_num']     = $goods_num[$key];
            $limit_goods[$key]['limit_num']     = $limit_num[$key];
            $limit_goods[$key]['promote_price'] = $promote_price[$key];
		}
		//写入数据
		foreach ($limit_goods as $key => $value) {
			// 抽取库存作为活动库存
            // change_goods_storage($value['goods_sku'],3,-$value['goods_num']);
            if (!change_goods_storage($value['goods_sku'],3,-$value['goods_num'])) {
                $links[] = array('href' => 'limit.php?act=list', 'text' => "商品库存不足");
                sys_msg("商品库存不足", 100, $links);
            }
			//插入限购表记录
			$sql = ' INSERT INTO ' . $ecs->table('limit') . ' (goods_id, limit_num,goods_num,goods_sku,area_id,start_time,end_time,promote_price) ' .
    				" VALUES('$value[goods_id]', '$value[limit_num]','$value[goods_num]','$value[goods_sku]','$value[area_id]','$promote_start_date','$promote_end_date','$value[promote_price]')";
    		$db->query($sql);
            //更新促销商品
            $sql =  " UPDATE ".$GLOBALS['ecs']->table('goods').
                    " set promote_price=$value[promote_price],promote_start_date = $promote_start_date ,promote_end_date = $promote_end_date,is_promote=1 ".
                    " WHERE goods_id = $value[goods_id] ";
            $db->query($sql);
		}
		header("Location: limit.php?act=list");
	}
	$smarty->display('limit_add.htm');
}

//获取闪购商品

if($_REQUEST['act'] == "add_goods"){

	$keyword=$_REQUEST['keyword'];
    $area_id=empty($_REQUEST['area_id'])?3:$_REQUEST['area_id'];
	$where .= " AND (g.goods_id LIKE '%" . mysql_like_quote($keyword) . "%' OR g.goods_sku LIKE '%" . mysql_like_quote($keyword) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($keyword) . "%')";
    $sql=" SELECT g.goods_id,g.goods_name, ga.agency_name,g.shop_price,g.promote_start_date,g.promote_end_date,g.goods_sku ".
		 " FROM ".$GLOBALS['ecs']->table('goods') ." AS g ".
		 " LEFT JOIN ". $GLOBALS['ecs']->table('agency') ." AS ga ON agency_id = $area_id ".
		 " WHERE  g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".$where;

	$goods_list=$db->getAll($sql);
    /*读取内存库存*/
    foreach ($goods_list as $key => $value) {
        $goods_list[$key]['goods_stock'] = $GLOBALS['virtualStock']->selectStock($value['goods_sku']);
    }
    // dump($goods_list);

	$smarty->assign('goods_list',   $goods_list);
    $return=$smarty->fetch('limit_add_goods.htm');
    echo json_encode($return);
    exit();
}

//编辑闪购商品
if($_REQUEST['act'] == "edit_limit"){
    $goods_num = !empty($_REQUEST['goods_num'])?$_REQUEST['goods_num']:""; //闪购数量
    $limit_num = !empty($_REQUEST['limit_num'])?$_REQUEST['limit_num']:""; //限制数量
    $promote_price = !empty($_REQUEST['promote_price'])?$_REQUEST['promote_price']:""; //闪购价
    $buy_number = !empty($_REQUEST['buy_number'])?$_REQUEST['buy_number']:"0"; //显示被买数
    $limit_id  = !empty($_REQUEST['limit_id'])?$_REQUEST['limit_id']:""; //闪购ID

    $return['error'] = 0;
    $return['content'] = "";
    //查询原闪购信息


    $sql ="SELECT * FROM ".$GLOBALS['ecs']->table('limit') ." WHERE limit_id = $limit_id AND is_stock = 0 ";
    $limit_info=$db->getRow($sql);
    if(empty($limit_info)){
        $return['error'] = 2;
        $return['content'] = "改闪购商品已结算或不存在"; 
        echo json_encode($return);
        exit();
    }

    //比较修改
    //如果闪购数比原闪购数大则再扣取库存
    if($goods_num>$limit_info['goods_num']){
            $num = $goods_num-$limit_info['goods_num'];
            //减少库存
            if (!change_goods_storage($limit_info['goods_sku'],3,-$num)) {
                $return['error'] = 2;
                $return['content'] = "商品剩余库存不足"; 
                echo json_encode($return);
                exit();
            }
    }
    //如果闪购数比原闪购数少则返回库存
    if($goods_num<$limit_info['goods_num']){
            $num = $limit_info['goods_num']-$goods_num;
            change_goods_storage($limit_info['goods_sku'],3,$num);
    }

    //修改其他信息
    $sql =  " UPDATE ".$GLOBALS['ecs']->table('limit').
                    " set goods_num=$goods_num , limit_num = $limit_num , promote_price=$promote_price , buy_number = $buy_number ".
                    " WHERE limit_id = $limit_id";            

    $db->query($sql); 

    //修改价格信息
    $sql =  " UPDATE ".$GLOBALS['ecs']->table('goods').
                    " set promote_price=$promote_price ".
                    " WHERE goods_sku = $limit_info[goods_sku] ";
                        $return['error'] = 1;
    $db->query($sql); 
    $return['error'] = 1;
    $return['content'] = "修改信息成功"; 
    echo json_encode($return);
    exit();

}
//清点库存
if($_REQUEST['act'] == "count_stock"){
    $limit_id  = !empty($_REQUEST['limit_id'])?$_REQUEST['limit_id']:""; //闪购ID
    //查询原闪购信息
    $sql ="SELECT * FROM ".$GLOBALS['ecs']->table('limit') ." WHERE limit_id = $limit_id AND is_stock = 0 ";
    $limit_info=$db->getRow($sql);
    if(empty($limit_info)){
        $return['error'] = 2;
        $return['content'] = "改闪购商品已结算或不存在"; 
        echo json_encode($return);
        exit();
    }

    if($limit_info['end_time']>time()){
        $return['error'] = 2;
        $return['content'] = "改闪购商品未过时不能清点"; 
        echo json_encode($return);
        exit();
    }






    //删除购物车中的闪购商品
    $sql =  " DELETE FROM ".$GLOBALS['ecs']->table('cart') .
            " WHERE goods_sku = $limit_info[goods_sku] AND extension_code = 'limit' AND area_id = $limit_info[area_id] ";
    $db->query($sql);




    //如果有剩余库存
    if($limit_info['goods_num']>$limit_info['buy_num']){
            $num = $limit_info['goods_num'] - $limit_info['buy_num'];
            change_goods_storage($limit_info['goods_sku'],3,$num);
    }
    $sql =  " UPDATE ".$GLOBALS['ecs']->table('limit').
        " set is_stock= 1 ".
        " WHERE limit_id = $limit_id ";
    $db->query($sql);
    $return['error'] = 1;
    $return['content'] = "清点库存成功"; 
    echo json_encode($return);
    exit();
}
//删除闪购库存
if($_REQUEST['act'] == "delete_stock"){
    $limit_id  = !empty($_REQUEST['limit_id'])?$_REQUEST['limit_id']:""; //闪购ID
    $sql ="SELECT * FROM ".$GLOBALS['ecs']->table('limit') ." WHERE limit_id = $limit_id AND is_stock = 0 ";
    $limit_info=$db->getRow($sql);
    if(empty($limit_info)){
        $return['error'] = 2;
        $return['content'] = "该记录不存在"; 
        echo json_encode($return);
        exit();
    }


    //如果有剩余库存
    if($limit_info['goods_num']>$limit_info['buy_num']){
            $num = $limit_info['goods_num'] - $limit_info['buy_num'];
            change_goods_storage($limit_info['goods_sku'],3,$num);
    }
    //更新闪购信息
    $sql =  " UPDATE ".$GLOBALS['ecs']->table('goods').
            " set promote_price=0,promote_start_date = 0 ,promote_end_date = 0,is_promote=0".
            " WHERE goods_id = $limit_info[goods_id] ";
    $db->query($sql);
    //删除闪购信息
    $sql =  " DELETE FROM".$GLOBALS['ecs']->table('limit').
            " WHERE limit_id = $limit_id ";
    $db->query($sql);
    $return['error'] = 1;
    $return['content'] = "删除成功"; 
    echo json_encode($return);
    exit();



}












//获取闪购列表

function limit_list(){

	    $filter['promote_start_date']        = empty($_REQUEST['promote_start_date']) ? '' : strtotime($_REQUEST['promote_start_date']);//缺货筛选
        $filter['promote_end_date']          = empty($_REQUEST['promote_end_date']) ? '' : strtotime($_REQUEST['promote_end_date']);
        $filter['area_id']          		 = empty($_REQUEST['area_id']) ? 0 : intval($_REQUEST['area_id']);
        $filter['keyword']                   = empty($_REQUEST['keyword']) ? "" : $_REQUEST['keyword'];
        $where = 'WHERE g.is_delete = 0 ';
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND (g.goods_id LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR gs.goods_sku LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }
        /*地区*/
        if(!empty($filter['area_id'])){
        	 $where .=" AND l.area_id = $filter[area_id] ";
        }
        /*时间*/
        if(!empty($filter['promote_start_date'])&&!empty($filter['promote_end_date'])){
        	$where .=" AND l.start_time >= $filter[promote_start_date]  AND l.start_time <= $filter[promote_end_date]";
        }



        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }
        //查询总页数

        $sql = " SELECT g.goods_id,g.goods_name,g.goods_sku,sa.area_name,gs.goods_number as goods_stock,l.buy_number,l.promote_price,l.limit_id,l.is_stock,l.goods_num,l.limit_num,l.buy_num,l.car_num,l.start_time , l.end_time ".
                " FROM ". $GLOBALS['ecs']->table('limit') ."AS l".
                " LEFT JOIN ".$GLOBALS['ecs']->table('goods')." AS g ON g.goods_id=l.goods_id".
                " LEFT JOIN ".$GLOBALS['ecs']->table('goods_stock')." AS gs ON gs.goods_id=l.goods_id AND gs.area_id = l.area_id".
                " LEFT JOIN ".$GLOBALS['ecs']->table('service_area')." AS sa ON sa.area_id=l.area_id ".
                $where.
                " ORDER BY  l.start_time  DESC ";
        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']   = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1; // 总页码
        $sql .= " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]"; // 调取页码数量



        $row = $GLOBALS['db']->getAll($sql);
        //格式化数据
        foreach ($row as $key => $value) {
            $row[$key]['promote_start_date'] = date('Y-m-d-H:s',$value['start_time']);
            $row[$key]['promote_end_date']   = date('Y-m-d-H:s',$value['end_time']);
            $row[$key]['goods_stock']        = $GLOBALS['virtualStock']->selectStock($value['goods_sku']);
        }




        $arr = array('goods' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}




 ?>